﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Abp.Domain.Entities;
using Abp.UI;
using JetBrains.Annotations;

namespace DHJ.Cost.Excel
{
    public class ExcelItemData: Entity<Guid>
    {
        public Guid ExcelDataId { get; set; }
        [ForeignKey("ExcelDataId")]
        public ExcelData ExcelData { get; set; }

        public int ItemIndex { get; set; }

        [CanBeNull]
        [MaxLength, Column(TypeName = "ntext")]
        public byte[] Data { get; set; }

        public List<ExcelCell> Cells
        {
            get
            {
                if (Data == null || Data.Length == 0)
                    return new List<ExcelCell>();
                try
                {
                    using (MemoryStream stream = new MemoryStream(Data))
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        //把对象序列化到流中
                        return (List<ExcelCell>)bf.Deserialize(stream);
                    }
                }
                catch (Exception)
                {
                    return new List<ExcelCell>();
                }
            }

            set
            {
                if (value == null || value.Count == 0)
                    Data = null;
                else
                {
                    try
                    {
                        using (MemoryStream stream = new MemoryStream())
                        {
                            BinaryFormatter bf = new BinaryFormatter();
                            //把对象序列化到流中
                            bf.Serialize(stream, value);
                            Data = stream.ToArray();
                        }
                    }
                    catch (Exception e)
                    {
                        throw new UserFriendlyException("管道序列化出错" + e.Message);
                    }
                }
            }
        }
    }
}
